package backend.dal.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backend.dal.DALException;
import backend.util.PropertyProvider;

public final class ConnectionManager {

	private final static Integer SIZE = Integer
			.parseInt(PropertyProvider.INSTANCE.getProperty("SIZE"));
	private static final Logger LOG = LoggerFactory
			.getLogger(ConnectionManager.class);
	private final List<Connection> pool;
	private static ConnectionManager instance;

	private ConnectionManager() {
		pool = new LinkedList<Connection>();
		initializePool();
	}

	public synchronized static ConnectionManager getInstance() {
		if (instance == null) {
			instance = new ConnectionManager();
		}
		return instance;
	}

	public synchronized Connection getConnection() throws DALException {
		Connection con = null;
		if (pool.size() > 0) {
			con = pool.get(0);
			pool.remove(0);
		}
		if (con == null) {
			throw new DALException("No connections in pool");
		}
		return con;
	}

	public synchronized void returnConnection(final Connection con) {
		if (pool.size() < SIZE) {
			pool.add(con);
		}
	}

	private void initializePool() {
		String dbURL = PropertyProvider.INSTANCE.getProperty("dbURL");
		String dbUser = PropertyProvider.INSTANCE.getProperty("dbUser");
		String dbPassword = PropertyProvider.INSTANCE.getProperty("dbPassword");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			for (int i = 0; i < SIZE; i++) {
				pool.add(DriverManager.getConnection(dbURL, dbUser, dbPassword));
			}
			LOG.info(SIZE + " connections added to pool");
		} catch (final SQLException e) {
			JOptionPane.showMessageDialog(new JFrame(),
					"Sql server not running");
			System.exit(0);
		} catch (ClassNotFoundException e) {
			LOG.error("Connection pool initialization failed", e);
			throw new DALException("Connection pool initialization failed", e);
		}
			
			

		
	}
}
